package com.wms.service.impl;

import com.wms.entity.StoreReturn;
import com.wms.entity.StoreReturnDTO;
import com.wms.enums.ReturnStatus;
import com.wms.mapper.StoreReturnMapper;
import com.wms.service.StoreReturnService;
import com.wms.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author TianWenHe
 * @date 2025/4/27
 * @desc
 */
@Service
public class StoreReturnServiceImpl implements StoreReturnService {

    @Autowired
    private StoreReturnMapper storeReturnMapper;
    private static final String IMAGE_PREFIX = "https://jinghaiyang.oss-cn-beijing.aliyuncs.com/app/upload/";

    @Override
    public List<StoreReturn> find(StoreReturnDTO storeReturnDTO) {
        return storeReturnMapper.find(storeReturnDTO);
    }

    @Override
    public Long add(StoreReturn storeReturn) {
        // 处理图片URL前缀
        if (storeReturn.getImage() != null && storeReturn.getImage().startsWith(IMAGE_PREFIX)) {
            storeReturn.setImage(storeReturn.getImage().replace(IMAGE_PREFIX, ""));
        }
        // 统一设置创建时间
        storeReturn.setCreateTime(DateUtils.addFixedEightHours(new Date()));

        storeReturnMapper.add(storeReturn);
        return storeReturn.getId();
    }

    @Override
    public void update(StoreReturn storeReturn) {
        // 处理图片URL前缀
        if (storeReturn.getImage() != null && storeReturn.getImage().startsWith(IMAGE_PREFIX)) {
            storeReturn.setImage(storeReturn.getImage().replace(IMAGE_PREFIX, ""));
        }
        // 如果状态为“待入库”且没有设置sorting_time，则设置sorting_time
        if (storeReturn.getStatus().equals(ReturnStatus.TO_BE_STORED.getDescription()) && storeReturn.getSortingTime() == null) {
            storeReturn.setSortingTime(DateUtils.addFixedEightHours(new Date()));
        }

        // 如果状态为“部分入库”且没有设置storage_time，则设置storage_time
        if (storeReturn.getStatus().equals(ReturnStatus.PARTIALLY_STORED.getDescription()) && storeReturn.getStorageTime() == null) {
            storeReturn.setStorageTime(DateUtils.addFixedEightHours(new Date()));
        }

        storeReturnMapper.update(storeReturn);
    }

    @Override
    public void delete(List<Long> ids) {
        storeReturnMapper.delete(ids);
    }

    @Override
    public void insertBatch(List<StoreReturn> storeReturns) {
        // 统一设置创建时间
        for (StoreReturn storeReturn : storeReturns) {
            storeReturn.setCreateTime(DateUtils.addFixedEightHours(new Date()));
        }
        storeReturnMapper.insertBatch(storeReturns);
    }
}
